import { fromError } from 'zod-validation-error'
import bcrypt from 'bcryptjs'
import { createUserSchema, usersTable } from '~~/server/db/schema/user'
import { db } from '~~/server/db'
import type { QueryError } from 'mysql2'

export default defineEventHandler(async (event) => {
  const validationResult = await readValidatedBody(event, (body) =>
    createUserSchema.safeParse(body)
  )

  if (!validationResult.success) {
    throw createError({
      statusCode: 400,
      message: fromError(validationResult.error).toString()
    })
  }

  const { phone, remark = '', role, status, name } = validationResult.data

  try {
    // 加密密码
    const salt = await bcrypt.genSalt(10)
    const passwordHash = await bcrypt.hash(phone.slice(phone.length - 6, phone.length), salt)

    // 创建用户
    const [newUser] = await db
      .insert(usersTable)
      .values({
        phone,
        name,
        password: passwordHash,
        role,
        status,
        remark
      })
      .$returningId()
    setResponseStatus(event, 201)
    return {
      message: '用户创建成功',
      data: newUser.id
    }
  } catch (error: any) {
    if ((error as QueryError).code === 'ER_DUP_ENTRY') {
      throw createError({
        statusCode: 409,
        message: '手机号已存在'
      })
    }
    console.error('Create user error:', error)
    throw createError({
      statusCode: 500,
      message: '创建用户失败'
    })
  }
})
